﻿CREATE PROCEDURE [dbo].[WriteOffLinesUpdate]
(--списание товара
	@Qntty int,
	@RetailSum decimal(19, 2),
	@RepriceWriteoffReasonId int, --код причины списания/переоценки
	@RepriceWriteoffReasonText  varchar(50),--причина для кода 4 
	@QualityLossMark varchar(50), --признак понижения качества
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@Original_Id int,
	@Original_MD datetime
) --Нельзя менять партиию в строке документа по списанию товара!
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intRowCount int
DECLARE @intDocTypeId int, @orgDocDate smalldatetime, @datInputDocDate smalldatetime
DECLARE @orgQntty int, @orgPartyId int, @orgRetailSum decimal(19, 2)
DECLARE @intInputCount int, @intOutputCount int, @intGoodsDocLineId int

SET NOCOUNT ON
IF (@Original_Id Is Null) OR (@Original_MD Is Null) OR (@Qntty Is Null) OR (@RetailSum Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <=0) OR (@RetailSum <=0)
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Количество и сумма д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @orgDocDate = D.DocDate, @intDocTypeId = D.DocTypeId, @intGoodsDocLineId = GoodsDocLineId,
@orgRetailSum = 0.0 - L.RetailSum, @orgQntty = 0 - L.Qntty, @orgPartyId = PartyId
FROM dbo.vwWriteoffLines L INNER JOIN [CA].[Documents] D ON D.Id = L.DocId
WHERE L.Id = @Original_Id AND L.MD = @Original_MD

IF (@@rowcount <> 1)
BEGIN
	SELECT @intErrCode = 3, 
	@strMsg = 'Данные изменены после последнего запроса!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 9)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Неправильный тип документа с идентификатором !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

--проверка товародвижения
SET @intErrCode = 0 - (@Qntty + @orgQntty)
IF @intErrCode < 0
BEGIN
	EXEC @intRet = dbo.CheckPartyFlow @orgPartyId, @intErrCode, @orgDocDate, @intInputCount OUTPUT, @intOutputCount OUTPUT
	IF @intRet <> 0 RETURN @intRet
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT

BEGIN TRAN

IF (@orgRetailSum <> (0.0 - @RetailSum) ) OR (@orgQntty <> (0 - @Qntty) )
BEGIN
	UPDATE [CA].[GoodsDocLines] SET 
	[Qntty] = 0 - @Qntty, [RetailSum] = 0.0 - @RetailSum, 
	[MD] = @MD, [MW] = @MW 
	WHERE Id = @intGoodsDocLineId

	SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	IF @intErrCode <> 0 
	BEGIN
		ROLLBACK TRAN
		RETURN @intErrCode
	END
	IF (@intRowCount <> 1)
	BEGIN
		IF @@trancount > 0 ROLLBACK TRAN
		SELECT @intErrCode = 5, 
		@strMsg = 'Запись в таблице товародвижения не изменена!'
		RAISERROR (@strMsg, 11, 1)
		RETURN @intErrCode
	END

END

	SET NOCOUNT OFF;

UPDATE CD.RepriceWriteoffLines SET 
RepriceWriteoffReasonId = @RepriceWriteoffReasonId,
RepriceWriteoffReasonText = @RepriceWriteoffReasonText,
QualityLossMark = @QualityLossMark,
[Note] = @Note, [MD] = @MD, [MW] = @MW 
WHERE Id = @Original_Id ;

SELECT @intErrCode = @@error, @intRowCount = @@rowcount

	SET NOCOUNT ON;

IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 6, 
	@strMsg = 'Запись в таблице списания/переоценки не изменена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

COMMIT TRAN

	SET NOCOUNT OFF;
SELECT Id, DocId, PartyId, Qntty, RetailSum, ReturnLineId, 
GoodsDocLineId, RepriceWriteoffReasonId, RepriceWriteoffReasonName, 
RepriceWriteoffReasonText, QualityLossMark, Note, MD, MW
FROM dbo.vwWriteoffLines WHERE Id = @Original_Id

RETURN 0